package net.pet.biz.admin.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.pet.biz.admin.AdminUserService;
import net.pet.dal.mapper.admin.AdminUserMapper;
import net.pet.dal.mapper.admin.ResourceMapper;
import net.pet.dto.admin.AdminUser;
import net.pet.dto.admin.Resource;
import net.pet.util.PWDEncode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminUserServiceImpl implements AdminUserService{
	@Autowired 
	private AdminUserMapper adminUserMapper;
	@Autowired
	private ResourceMapper resourceMapper;

	@Override
	public boolean login(AdminUser user) {
		String pwd = PWDEncode.encode(user.getPassword());
		user = adminUserMapper.getUserByName(user.getAdminName());
		if(user == null){
			return false;
		}
		if(pwd.equals(user.getPassword())){
			return true;
		}
		return false;
	}

	@Override
	public AdminUser getMenus(AdminUser user) {
		List<Resource> resourceList = null;
		if("tom".equals(user.getAdminName())){
			Resource resource = new Resource();
			resource.setResourceStatus(1);
			resourceList = resourceMapper.find(resource);
		}else{
			resourceList = resourceMapper.findByUser(user);
		}
		//整理资源
		List<Resource> menuList = new ArrayList<Resource>();
		Map<Integer,List<Resource>> subMenu = new HashMap<Integer,List<Resource>>();
		for (Resource resource : resourceList) {
			//只做菜单
			if(resource.getResourceType()==Resource.MENU){
				if(resource.getParentId() == null){
					menuList.add(resource);
				}else{
					List<Resource> subList = subMenu.get(resource.getParentId());
					if(subList == null)
						subList = new ArrayList<Resource>();
					subList.add(resource);
					subMenu.put(resource.getParentId(),subList);
				}
			}
		}
		user.setMenuList(menuList);
		user.setSubMenu(subMenu);
		user.setResourceList(resourceList);
		return user;
	}
}